<template>
  <el-dialog
    title="添加用户"
    :visible.sync="dialogVisible"
    width="50%"
    @close="diologClose"
    :close-on-click-modal="false"
  >
    <!-- form表单 -->
    <el-form :model="permissionForm" :rules="rules" ref="addPermissionFormRef" label-width="100px">
      <!-- ID -->
      <el-form-item label="id" prop="id">
        <el-input v-model="permissionForm.id" disabled></el-input>
      </el-form-item>

      <!-- 用户名 -->
      <el-form-item label="权限名" prop="permissionName">
        <el-input v-model="permissionForm.permissionName"></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item label="权限url" prop="url">
        <el-input v-model="permissionForm.url"></el-input>
      </el-form-item>
    </el-form>

    <!-- 底部 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogFormCheckFunc">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 请求
import { getOnePermission, postUpdPermission } from '@/network/rightControlRequest.js'

export default {
  data() {
    return {
      dialogVisible: false,
      permissionForm: {},
      rules: {
        permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
        url: [{ required: true, message: '请输入权限url名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    /**
     * 关闭dialog回调
     */
    diologClose() {
      this.$refs['addPermissionFormRef'].clearValidate();
    },

    /**
     * 开启dialog回调
     */
    async openDialog(id) {
      this.dialogVisible = true

      // 请求
      const { data, meta } = await getOnePermission(id)
      if (meta.status != 200) {
        return this.$message.error(meta.msg)
      }
      this.permissionForm = data.permission
    },

    /**
     * 提交表单
     */
    async dialogFormCheckFunc() {
      const ret = await this.$refs['addPermissionFormRef'].validate();
      if (!ret) { return this.$message.error('请将表单填写完整'); }

      // 请求
      const {meta} = await postUpdPermission(this.permissionForm);
      if (meta.status != 200) { return this.$message.error(meta.msg); }
      this.$bus.$emit('getRightList');
      this.dialogVisible = false;
      return this.$message.success(meta.msg);
    }
  },

  created() {
    this.$bus.$on('openUpdDialog', id => this.openDialog(id))
  },
  destroyed() {
    this.$bus.$off('openUpdDialog')
  }
}
</script>

